package org.example.netty.handler.channel;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.example.netty.model.CustomMessage;
import org.example.netty.constant.ProtocolConstants;

import java.util.List;

/**
 * @author:hzc
 * @date:2025/5/23
 * @desc: 自定义协议的解码器
 */
public class CustomProtocolDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        //读取到协议头的长度
        if (in.readableBytes()<21){
            return;
        }
        in.markReaderIndex();//标记当前读取的位置
        short magic=in.readShort();//是否在这里直接判断magic
        if (magic!= ProtocolConstants.MAGIC){
            System.out.println("非法的魔数"+magic);
            //todo 是跳过该条消息还是直接关闭，我感觉还是关闭比较合适
            //todo 为了防止是自己代码问题我感觉我需要去给个响应
            ctx.close();
            return;
        }
        byte version=in.readByte();
        //todo 记得校验版本，版本不对记得告诉对方
        byte serializeAlgo=in.readByte();
        int reserved=in.readInt();
        byte type=in.readByte();
        long requestId = in.readLong();
        int length=in.readInt();
        //
        if (in.readableBytes()<length){
            in.resetReaderIndex();//内容没到期，重回标记点
            return;
        }
        byte[] content=new byte[length];
        in.readBytes(content);
        CustomMessage message = new CustomMessage();
        message.setMagic(magic);
        message.setVersion(version);
        message.setSerializeAlgo(serializeAlgo);
        message.setReserved(reserved);
        message.setType(type);
        message.setRequestId(requestId);
        message.setLength(length);
        message.setContent(content);
        out.add(message);
    }
}
